<template>
  <div class="user-manage">
    <!-- 页面标题与操作按钮 -->
    <div class="page-header">
      <h2 class="page-title">用户管理</h2>
      <div class="action-buttons">
        <el-button type="primary" @click="openAddDialog" size="small">新增用户</el-button>
        <el-button type="danger" @click="handleDelete" :disabled="selectedIds.length === 0" size="small">删除</el-button>
        <el-button type="info" size="small">报表</el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      highlight-current-row
      class="user-table"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="userId" label="用户ID" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="80"></el-table-column>
      <el-table-column prop="academy" label="学院" width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="120"></el-table-column>
      <el-table-column prop="email" label="电子邮箱" width="180"></el-table-column>
      <el-table-column prop="avatar" label="头像" width="80">
        <template #default="scope">
          <el-image 
            :src="scope.row.avatar || 'https://i.pravatar.cc/60?u=default'" 
            fit="cover"
            :preview-src-list="[scope.row.avatar || 'https://i.pravatar.cc/300?u=default']"
            class="user-avatar"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色" width="80">
        <template #default="scope">
          <el-tag :type="getRoleType(scope.row.role)">{{ getRoleText(scope.row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button type="primary" plain size="mini" @click="openEditDialog(scope.row)">修改</el-button>
          <el-button type="danger" plain size="mini" @click="handleDeleteSingle(scope.row.userId)">删除</el-button>
          <el-button type="info" plain size="mini" @click="resetPassword(scope.row.userId)">重置密码</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog 
      :title="dialogType === 'edit' ? '编辑用户' : '新增用户'" 
      v-model="dialogVisible" 
      width="600px" 
      class="user-dialog"
    >
      <el-form :model="form" label-width="120px" :rules="rules" ref="formRef">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" :disabled="dialogType === 'edit'" placeholder="请输入用户ID"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="学院" prop="academy">
          <el-select v-model="form.academy" placeholder="请选择学院" style="width: 100%">
            <el-option label="计算机科学与计算" value="计算机科学与计算"></el-option>
            <el-option label="计算机科学与技术" value="计算机科学与技术"></el-option>
            <el-option label="计算机信息与计算学院" value="计算机信息与计算学院"></el-option>
            <el-option label="信息工程学院" value="信息工程学院"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-radio-group v-model="form.role">
            <el-radio label="0">普通用户</el-radio>
            <el-radio label="1">管理员</el-radio>
            <el-radio label="2">超级管理员</el-radio>
            <el-radio label="3">其他角色</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <div class="avatar-display">
            <el-image 
              :src="form.avatar || 'https://i.pravatar.cc/100?u=default'" 
              fit="cover"
              class="avatar"
            ></el-image>
          </div>
          <div class="el-form-item__error" style="text-align: center;">
            {{ dialogType === 'edit' ? '头像不可修改' : '新增用户默认头像' }}
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">
            {{ dialogType === 'edit' ? '保存' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog title="重置密码" :visible.sync="resetPwdVisible" width="400px">
      <el-form :model="resetPwdForm" label-width="120px" ref="resetPwdFormRef">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="resetPwdForm.newPassword" type="password" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" type="password" placeholder="请确认新密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetPwdVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmResetPassword">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import axios from 'axios'

// 后端API路径
const baseUrl = 'http://172.20.10.2:8080/api/user'

// 状态管理
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])
const dialogVisible = ref(false)
const dialogType = ref('edit') // 'edit' 或 'add'

// 表单数据
const form = reactive({
  userId: '',
  name: '',
  academy: '',
  role: '0',
  phone: '',
  email: '',
  avatar: ''
})
const formRef = ref(null)

// 重置密码表单
const resetPwdVisible = ref(false)
const resetPwdForm = reactive({
  userId: '',
  newPassword: '',
  confirmPassword: ''
})
const resetPwdFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  userId: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  academy: [
    { required: true, message: '请选择学院', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
})

// 角色转换工具
const getRoleText = (role) => {
  const roleMap = {
    '0': '普通用户',
    '1': '管理员',
    '2': '超级管理员',
    '3': '其他角色'
  }
  return roleMap[role] || `未知角色(${role})`
}

const getRoleType = (role) => {
  const typeMap = {
    '0': 'info',
    '1': 'warning',
    '2': 'danger',
    '3': 'primary'
  }
  return typeMap[role] || 'default'
}

// 加载用户列表
const loadUserList = async () => {
  try {
    const res = await axios.get(`${baseUrl}/page`, {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    if (res.data.code === 200) {
      tableData.value = res.data.data.list || []
      total.value = res.data.data.total || 0
      ElMessage.success('加载成功')
    } else {
      throw new Error(res.data.message || '加载失败')
    }
  } catch (error) {
    console.error('加载用户列表失败', error)
    ElMessage.error(error.message || '加载失败，请稍后重试')
  }
}

// 分页控制
const handleSizeChange = (val) => {
  pageSize.value = val
  loadUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadUserList()
}

// 批量删除
const handleDelete = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  ElMessageBox.confirm(
    `此操作将永久删除选中的 ${selectedIds.value.length} 个用户，是否继续?`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await axios.delete(`${baseUrl}/batch`, { 
        data: selectedIds.value 
      })
      
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        loadUserList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 单个删除
const handleDeleteSingle = (userId) => {
  ElMessageBox.confirm(
    '此操作将永久删除该用户，是否继续?',
    '提示',
    {
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await axios.delete(`${baseUrl}/${userId}`)
      
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        loadUserList()
      } else {
        ElMessage.error(res.data.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 打开编辑弹窗
const openEditDialog = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
  
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 打开新增弹窗
const openAddDialog = () => {
  dialogType.value = 'add'
  // 清空表单并保留默认值
  form.userId = ''
  form.name = ''
  form.academy = ''
  form.role = '0'
  form.phone = ''
  form.email = ''
  form.avatar = '' // 新增用户使用默认头像
  
  dialogVisible.value = true
  
  nextTick(() => {
    formRef.value?.resetFields()
  })
}

// 保存（编辑/新增）
const handleSave = async () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return false
    
    try {
      let res
      if (dialogType.value === 'add') {
        // 新增用户（不传递头像字段，使用默认值）
        res = await axios.post(`${baseUrl}/add`, {
          userId: form.userId,
          name: form.name,
          academy: form.academy,
          role: form.role,
          phone: form.phone,
          email: form.email
        })
      } else {
        // 编辑用户（保留原有头像）
        res = await axios.put(`${baseUrl}/update`, form)
      }
      
      if (res.data.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '新增用户成功' : '修改成功')
        dialogVisible.value = false
        loadUserList()
      } else {
        ElMessage.error(res.data.message || '操作失败')
      }
    } catch (error) {
      console.error(dialogType.value === 'add' ? '新增失败' : '保存失败', error)
      ElMessage.error('操作失败，请稍后重试')
    }
  })
}

// 重置密码
const resetPassword = (userId) => {
  resetPwdForm.userId = userId
  resetPwdVisible.value = true
  
  nextTick(() => {
    resetPwdFormRef.value?.resetFields()
  })
}

// 确认重置密码
const confirmResetPassword = async () => {
  resetPwdFormRef.value?.validate(async (valid) => {
    if (!valid) return false
    
    if (resetPwdForm.newPassword !== resetPwdForm.confirmPassword) {
      ElMessage.error('两次输入的密码不一致')
      return
    }
    
    try {
      const res = await axios.post(`${baseUrl}/resetPassword`, {
        userId: resetPwdForm.userId,
        password: resetPwdForm.newPassword
      })
      
      if (res.data.code === 200) {
        ElMessage.success('密码重置成功')
        resetPwdVisible.value = false
      } else {
        ElMessage.error(res.data.message || '密码重置失败')
      }
    } catch (error) {
      console.error('密码重置失败', error)
      ElMessage.error('密码重置失败，请稍后重试')
    }
  })
}

// 初始化加载
nextTick(() => {
  loadUserList()
})
</script>

<style scoped>
/* 基础布局样式 */
.user-manage {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

/* 页面标题区域 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.page-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 表格样式优化 */
.user-table {
  margin-top: 16px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 12, 40, 0.05);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

/* 表单样式优化 */
.user-dialog .el-dialog__header {
  background-color: #f0f2f5;
  border-bottom: 1px solid #ebeef5;
}

.user-dialog .el-dialog__title {
  font-size: 18px;
  font-weight: 600;
}

.avatar-display {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #fff;
  box-shadow: 0 0 0 2px #ebf5ff;
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-manage {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
  
  .action-buttons .el-button {
    margin-right: 8px;
    margin-bottom: 8px;
  }
}
</style>